<?php

/*

    MMetaverse - Open Metaverse Web Manager

    Copyright (c) 2009 Mary Jane Soft - Marlon J. Manrique

    http://www.maryjanesoft.com
    http://www.marlonj.com

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Lesser General Public
    License as published by the Free Software Foundation; either
    version 2.1 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General
    Public License along with this library; if not, write to the
    Free Software Foundation, Inc., 59 Temple Place, Suite 330,
    Boston, MA  02111-1307  USA

    $Id$

*/

Yii::import('application.components.mmetaverse.MUserIdentity');

/**
 * Login form, ask for firstname, lastname and password 
 *
 */
class MLoginFormModel extends CFormModel {

    /**
     * User first name
     * @var string
     */
    public $firstName;

    /**
     * User last name 
     * @var string 
     */
    public $lastName;

    /**
     * User password
     * @var string
     */
    public $password;

    /**
     * Returns the validation rules for attributes.
     * @return array validation rules to be applied when validate() is called.
     */
    public function rules() {
        return array
        (
            // Required fields 
            array('firstName, lastName','required'),
            // Actions 
            array('password','authenticate')
        );
    }

    /**
     * Authenticate the user using the user identity manager
     * 
     * @param <type> $attribute the name of the attribute to be validated
     * @param <type> $params array options specified in the validation rule
     */
    public function authenticate($attribute, $params) {
        // If no errors authenticate the user 
        if(!$this->hasErrors()) {
            try {
                // Create the user identity provider
                $userIdentity = new MUserIdentity(
                    $this->firstName, $this->lastName, $this->password);

                // Authenticate the user
                $userIdentity->authenticate();

                // If authentication is done, set user indetity
                if($userIdentity->errorCode == CUserIdentity::ERROR_NONE) {
                    $duration = 0;
                    Yii::app()->user->login($userIdentity,$duration);
                }
                // Show error
                else {
                    $this->addError('firstName','Invalid User Info');
                }
            } catch (Exception $e) {
                $this->addError('firstName',$e->getMessage());
            }
        }
    }
}

?>
